package cn.crm.system.service.impl;

import cn.crm.common.annotation.DataScope;
import cn.crm.common.exception.ServiceException;
import cn.crm.common.utils.SecurityUtils;
import cn.crm.common.utils.StringUtils;
import cn.crm.common.utils.bean.BeanValidators;
import cn.crm.system.domain.pojo.dto.BusinessDto;
import cn.crm.system.domain.pojo.dto.ContactsDto;
import cn.crm.system.domain.pojo.dto.QuotedStatesDto;
import cn.crm.system.domain.pojo.entity.Business;
import cn.crm.system.domain.pojo.entity.BusinessAndContactsUpdate;
import cn.crm.system.domain.pojo.entity.QuotedStates;
import cn.crm.system.domain.pojo.vo.BusinessVo;
import cn.crm.system.domain.pojo.vo.CaseVo;
import cn.crm.system.domain.pojo.vo.ContactsVo;
import cn.crm.system.domain.pojo.vo.QuotedStatesVo;
import cn.crm.system.mapper.*;
import cn.crm.system.service.IBusinessService;
import cn.crm.system.service.IQuotedStatesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 处理客户的接口
 */

@Slf4j
@Service
public class QuotedStatesServiceImpl implements IQuotedStatesService {

    @Autowired
    private QuotedStatesMapper quotedStatesMapper;

    /**
     * 开始添加报价单状态
     * @param quotedStatesDto
     * @return
     */
    @Override
    public int insertquotedStates(QuotedStatesDto quotedStatesDto) {
        // 通过quotedId查询是否存在记录
        QuotedStatesVo existingState = quotedStatesMapper.selectByQuotedId(quotedStatesDto.getQuotedId());

        // 设置操作人
        quotedStatesDto.setCreateBy(SecurityUtils.getUsername());

        QuotedStates quotedStates = new QuotedStates();
        BeanUtils.copyProperties(quotedStatesDto, quotedStates);

        int result;
        if (existingState != null) {
            // 存在记录，执行更新操作
            log.debug("更新报价单状态，quotedId: {}", quotedStatesDto.getQuotedId());
            quotedStates.setId(existingState.getId());
            quotedStates.setUpdateBy(SecurityUtils.getUsername());
            quotedStates.setUpdateTime(new Date());
            result = quotedStatesMapper.updateQuotedStates(quotedStates);
        } else {
            // 不存在记录，执行新增操作
            log.debug("新增报价单状态，quotedId: {}", quotedStatesDto.getQuotedId());
            quotedStates.setCreateTime(new Date());
            result = quotedStatesMapper.insertquotedStates(quotedStates);
        }

        return result;
    }
}

